package com.san.oms.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.san.base.domain.Tree;
import com.san.common.utils.BuildTree;
import com.san.oms.dao.ModelDao;
import com.san.oms.dao.ModelRoleDao;
import com.san.oms.domain.ModelRoleDO;
import com.san.oms.domain.ModelScDTO;
import com.san.oms.service.ModelRoleService;

@Service
public class ModelRoleServiceImpl implements ModelRoleService {
	
	@Autowired
	private ModelDao modelMapper;
	
	@Autowired
	private ModelRoleDao modelRoleMapper;
	
	@Override
	public Tree<ModelScDTO> getTree(Long deptId) {
		List<ModelScDTO> list = modelMapper.getAllModel();
		List<Long> modelIds = modelRoleMapper.listModelIdByDeptId(deptId);
		
		List<Tree<ModelScDTO>> trees = new ArrayList<Tree<ModelScDTO>>();
		for (ModelScDTO modelScDTO : list) {
			Tree<ModelScDTO> tree = new Tree<ModelScDTO>();
			tree.setId(modelScDTO.getModelId().toString());
			tree.setParentId("0");
			tree.setText(modelScDTO.getModelName());
			Map<String, Object> state = new HashMap<>(16);
			Long id = modelScDTO.getModelId();

			if (modelIds.contains(id)) {
				state.put("selected", true);
			} else {
				state.put("selected", false);
			}

			tree.setState(state);
			trees.add(tree);
		}
		// Constant.DICT_BUSI_TYPE_ID 业务类型ID
		Tree<ModelScDTO> t = BuildTree.build(trees, true, "0");
		return t;
		
	}

	@Override
	public int doEdit(ModelRoleDO modelRoleDO) {
		List<Long> modelIds = modelRoleDO.getModelIds();
		Long deptId = modelRoleDO.getDeptId();
		modelRoleMapper.removeByDeptId(deptId);
		List<ModelRoleDO> MRList = new ArrayList<>();
		for (Long modelId : modelIds) {
			ModelRoleDO mrDO = new ModelRoleDO();
			mrDO.setDeptId(deptId);
			mrDO.setModelId(modelId);
			MRList.add(mrDO);
		}
		if (MRList.size() > 0) {
			modelRoleMapper.batchSave(MRList);
		}
		
		return 0;
	}

	@Override
	public List<Long> modelList(Long deptId) throws Exception {
		List<Long> modelIds = modelRoleMapper.modelList(deptId);
		return modelIds;
	}

}
